import {inject, provide, ref} from "vue";
import {showError, showSuccess} from "../utils/notify";
import {showDialog} from "../utils/dialog";
import {Tag} from "../types/tag";
import {Ref} from "@vue/reactivity";
import {PageResult} from "../types/pageResult";
import {PaginationConfig} from "../types/paginationConfig";
import {TableColumnDefine} from "../types/table-column";
import {datetimeFormat} from "../utils/time";
import {request} from "../utils/request/client";
import {Prefix} from "../types/prefix";

const TagSymbol = Symbol()
export const useTagProvider = () => {
    const tags = ref<Tag[]>([])
    const setTags = (value: Array<Tag>) => tags.value = value

    provide(TagSymbol, {
        tags,
        setTags,
    })
}

export const useTag = () => {
    // 注入响应式数据
    const tagContext: { tags: Ref<Tag[]>; setTags: (value: Array<Tag>) => void } | undefined = inject(TagSymbol)
    if (!tagContext) {
        throw new Error('useTag Hook must be used after useTagProvider Hook')
    }
    const {tags, setTags} = tagContext

    // 数据加载状态
    const loading = ref<boolean>(true)

    const init = (): Tag => {
        return {
            id: -1,
            tagName: '',
            maxId: 0,
            step: 1000,
            description: '',
            updateTime: '',
            active: true,
            prefixId: -1
        } as Tag
    }

    const listPaging = async (no: number, size: number): Promise<PaginationConfig> => {
        loading.value = true
        try {
            if (!no || no < 0) {
                no = 1
            }
            if (!size || size < 0) {
                size = 10
            }
            const {data} = await request.get<PageResult<Tag>>(`/api/tag/list/${no}/${size}`)

            const {rows, pageNo, pageSize, totalCount} = data
            setTags(rows)
            return {
                page: pageNo,
                rowsPerPage: pageSize,
                rowsNumber: totalCount,
            } as PaginationConfig
        } finally {
            loading.value = false
        }
    }

    const add = async (tag: Tag): Promise<boolean> => {
        const {data} = await request.post<boolean>('/api/tag/add', tag)
        return data
    }

    const edit = async (tag: Tag): Promise<boolean> => {
        const {data} = await request.post<boolean>('/api/tag/edit', tag)
        return data
    }

    const getById = async (tagId: number): Promise<Tag> => {
        const {data} = await request.get<Tag>(`/api/tag/get/${tagId}`)
        return data
    }
    const remove = (tagId: number): void => {
        showDialog({
            title: '风险操作',
            message: '您确定要删除此标签吗？',
            cancel: true,
            persistent: true
        }).onOk(async () => {
            const {data: success} = await request.get<boolean>(`/api/tag/remove/${tagId}`)
            if (success) {
                setTags(tags.value.filter(tag => tag.id !== tagId))
                showSuccess('标签删除成功')
                return
            }
            showError("标签删除失败")
            return
        })
    }

    const switchById = async (tagId: number): Promise<void> => {
        const targetTag = tags.value.find(tag => tag.id === tagId)
        if (!targetTag) {
            return
        }
        const {data: success} = await request.get<boolean>(`/api/tag/switch/${tagId}`)
        if (!success) {
            showError(`标签${targetTag.active ? '禁用' : '启用'}失败`)
        }
        return
    }

    const prefixOptions = async (): Promise<Prefix[]> => {
        const {data} = await request.get<Prefix[]>('/api/prefix/list')
        data.unshift({
            id: -1,
            name: '无前缀',
            description: '不使用前缀'
        })
        return data
    }

    const tableColumns: Array<TableColumnDefine> = [
        {name:'tagName',align:'center',label:'标签名称',field:'tagName'},
        {name:'maxId',align:'center',label:'当前最大 ID',field:'maxId'},
        {name:'step',align:'center',label:'发号步长',field:'step'},
        {name:'description',align:'center',label:'标签描述',field:'description'},
        {name:'updateTime',align:'center',label:'最后更新时间',field:'updateTime',format:(val:any)=>{return datetimeFormat(val)}},
        {name:'active',align:'center',label:'状态',field:'active'},
        {name:'action',align:'center',label:'操作',field:'action'}
    ]

    return {
        ...tagContext,
        tableColumns,
        loading,
        init,
        listPaging,
        add,
        edit,
        getById,
        remove,
        switchById,
        prefixOptions
    }
}